<template>
  <div>
    <!-- 面包屑组件 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- 需要用native属性 -->
      <el-breadcrumb-item :to="{ path: '/home' }" @click.native="returnHome"
        >首页</el-breadcrumb-item
      >
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRole">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <!-- 展开去 -->
        <el-table-column type="expand">
          <!-- 插槽获取当前行的权限信息，可以用roleList拿，但还要区分行 -->
          <template v-slot="{ row }">
            <!-- 栅格系统 行数根据一级权限个数使用v-for渲染-->
            <el-row
              v-for="(right1, index1) in row.children"
              :class="['rowBottom', index1 == 0 ? 'rowTop' : '', 'vcenter']"
              :key="right1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5"
                ><el-tag closable @close="removeRightById(row, right1.id)">{{
                  right1.authName
                }}</el-tag
                ><i class="el-icon-caret-right"></i
              ></el-col>
              <!-- 二级权限、三级权限-->
              <el-col :span="19">
                <!-- 继续嵌套行列，进行二三级权限布局 -->
                <el-row
                  v-for="(right2, index2) in right1.children"
                  :class="[index2 == 0 ? '' : 'rowTop', 'vcenter']"
                  :key="right2.id"
                >
                  <!-- 二级 -->
                  <el-col :span="6"
                    ><el-tag
                      type="success"
                      closable
                      @close="removeRightById(row, right2.id)"
                    >
                      {{ right2.authName }}</el-tag
                    ><i class="el-icon-caret-right"></i
                  ></el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="right3 in right2.children"
                      :key="right3.id"
                      closable
                      @close="removeRightById(row, right3.id)"
                    >
                      {{ right3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <!-- 按钮区  v-slot="{ row }"-->
        <el-table-column label="操作" width="285px">
          <template v-slot="{ row }">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              @click="showEditDialog(row.id)"
              icon="el-icon-edit"
              size="mini"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRoleById(row.id)"
              >删除</el-button
            >
            <!-- tooltip文字消息的提示 -->
            <!-- 设置按钮 -->
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightsDialog(row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑会话框 -->
    <el-dialog title="编辑角色" :visible.sync="editRolesVisible" width="50%">
      <el-form
        :model="editRuleForm"
        :rules="editFormRules"
        ref="editForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRuleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRuleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="editFormClosed">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加会话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addRuleForm"
        :rules="addFormRules"
        ref="addForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRuleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRuleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFormClosed">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
    >
      <!-- 树形控件 根据层级显示数 -->
      <!-- 选中 默认改为绑定id值 -->
      <el-tree
        :data="rightsList"
        :props="rightsListProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defailtTree"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      rolesList: [],
      editRolesVisible: false,
      // 编辑区数据 、 校验规则
      editRuleForm: {},
      editFormRules: {
        roleDesc: [{
          required: true, message: '角色描述不能为空！', trigger: 'blur'
        }, {
          min: 5, max: 30, message: '描述信息在5到30个字符！', trigger: 'blur'
        }],
        roleName: [{
          required: true, message: '角色不能为空！'
        }, {
          min: 2, max: 8, message: '角色信息在2到8个字符！', trigger: 'blur'
        }]
      },
      // 添加校验规则
      addRuleForm: {
        roleDesc: '',
        roleName: ''
      },
      addFormRules: {
        roleDesc: [{
          required: true, message: '角色描述不能为空！', trigger: 'blur'
        }, {
          min: 5, max: 30, message: '描述信息在5到30个字符！', trigger: 'blur'
        }],
        roleName: [{
          required: true, message: '角色不能为空！'
        }, {
          min: 2, max: 8, message: '角色信息在2到8个字符！', trigger: 'blur'
        }]
      },
      addRolesVisible: false,
      setRightsDialogVisible: false,
      rightsList: [],
      // 绑定树形控件数据
      // 显示名称以及子级结构
      rightsListProps: {
        label: 'authName',
        children: 'children'
      },
      // 根据ele-ui默认开始选中
      // 只需要三级权限的id
      defailtTree: [],
      roleId: ''
    }
  },
  methods: {
    // 依然是点击首页的优化
    returnHome () {
      this.$bus.$emit('changePath')
    },
    async getRolesList () {
      const { data: res } = await this.$https.get('roles')
      if (res.meta.status === 200) {
        this.rolesList = res.data
      } else this.$message.error('数据请求失败！')
    },

    // 显示编辑会话框
    async showEditDialog (id) {
      this.editRolesVisible = true
      // 根据id请求数据渲染到初始会话框页面
      const { data: res } = await this.$https.get('roles/' + id)
      if (res.meta.status === 200) {
        // 请求成功
        // console.log(res)
        this.editRuleForm = res.data
      }
    },
    // 编辑预校验
    editFormClosed () {
      this.$refs.editForm.validate(async (validate) => {
        // 预校验成功
        if (validate) {
          const { data: res } = await this.$https.put('roles/' + this.editRuleForm.roleId, {
            roleName: this.editRuleForm.roleName,
            roleDesc: this.editRuleForm.roleDesc
          })
          this.editRolesVisible = false
          if (res.meta.status === 200) {
            this.$message.success('编辑成功！')
            this.getRolesList()
          } else this.$message.error('编辑失败！')
        }
      })
    },
    // 删除
    async deleteRoleById (id) {
      // 返回的是一个promise对象 确定返回confirm 否则返回cancel字符串
      const result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      // 发送删除请求 并刷新列表
      if (result === 'confirm') {
        const { data: res } = await this.$https.delete('roles/' + id)
        if (res.meta.status === 200) {
          this.$message.success('删除成功！')
        } else this.$message.error('删除失败！')
        this.getRolesList()
      }
    },
    // 添加角色
    addRole () {
      this.addRolesVisible = true
    },
    // 添加角色确定
    async addFormClosed () {
      const { data: res } = await this.$https.post('roles', this.addRuleForm)
      this.addRolesVisible = false
      if (res.meta.status === 201) {
        this.$message.success('添加成功！')
        this.getRolesList()
      } else this.$message.error('添加失败！')
    },
    // 取消添加重置列表
    addDialogClosed () {
      this.$refs.addForm.resetFields()
    },
    // 删除权限
    async removeRightById (role, rightId) {
      // 返回的是一个promise对象 确定返回confirm 否则返回cancel字符串
      const result = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      // 发送删除请求 并刷新列表
      if (result === 'confirm') {
        const { data: res } = await this.$https.delete('roles/' + role.id + '/rights/' + rightId)
        if (res.meta.status === 200) {
          this.$message.success('删除成功！')
          // 不调用获取方法，因为那会让整个页面刷新
          // 通过双向数据绑定，直接将最新的权限信息返回
          role.children = res.data
        } else this.$message.error('删除失败！')
      }
    },
    // 显示权限分配对话框
    async showSetRightsDialog (role) {
      // 获取当前角色所有权限列表
      const { data: res } = await this.$https.get('rights/tree')
      if (res.meta.status === 200) {
        // 通过树形结构获取权限列表
        this.rightsList = res.data
        this.roleId = role.id
        // console.log(this.rightsList)
        // 显示对话框之前将所有三级id获取
        // 先置空，防止点击不同的数据重合
        this.defailtTree = []
        this.getLeafId(role, this.defailtTree)
        this.setRightsDialogVisible = true
      } else this.$message.error('权限列表获取失败')
    },
    // 递归获取所有三级权限id
    getLeafId (node, arr) {
      if (!node.children) {
        arr.push(node.id)
        return arr
      } else {
        // 遍历孩子
        node.children.forEach(element => {
          this.getLeafId(element, arr)
        })
      }
    },
    // 分配权限确认
    async allotRights () {
      // 需要获得半选中、全选的id序列字符串且以逗号分隔
      // 通过getHalfCheckedKeys getCheckedKeys获取 解构赋值到一个新的数组里
      const keys = [
        ...this.$refs.treeRef.getHalfCheckedKeys(),
        ...this.$refs.treeRef.getCheckedKeys()
      ]
      // 通过逗号分隔 这是参数要求
      const idStr = keys.join(',')
      const { data: res } = await this.$https.post('roles/' + this.roleId + '/rights', { rids: idStr })
      if (res.meta.status === 200) {
        this.getRolesList()
        this.$message.success('分配成功！')
      } else this.$message.error('分配失败！')
      this.setRightsDialogVisible = false
    }
  },
  created () {
    // 创建时请求权限数据列表
    this.getRolesList()
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.rowBottom {
  border-bottom: 1px solid #eee;
}
.rowTop {
  border-top: 1px solid #eee;
}
// 每一行遍历都会添加
.vcenter {
  display: flex;
  align-items: center;
}
</style>
